package com.ppch.wuwamanus.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ppch.wuwamanus.annotation.AuthCheck;
import com.ppch.wuwamanus.common.BaseResponse;
import com.ppch.wuwamanus.common.ResultUtils;
import com.ppch.wuwamanus.exception.ErrorCode;
import com.ppch.wuwamanus.exception.ThrowUtils;
import com.ppch.wuwamanus.model.constant.UserConstant;
import com.ppch.wuwamanus.model.entity.ChatHistory;
import com.ppch.wuwamanus.model.entity.User;
import com.ppch.wuwamanus.model.enums.ChatHistoryMessageTypeEnum;
import com.ppch.wuwamanus.service.ChatHistoryService;
import com.ppch.wuwamanus.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;


/**
 * Package:ppch-picture-backend
 * ClassName:UserController
 *
 * @Author 泡泡茶壶
 * @Create 2024/12/17 18:10
 * @Version 1.0
 * Description:
 * 对话历史控制器类
 */
@RestController
@RequestMapping("/chat")
public class ChatHistoryController {

    @Resource
    private UserService userService;

    @Resource
    private ChatHistoryService chatHistoryService;


    /**
     * 分页查询某个用户的对话历史（游标查询）
     *
     * @param chatId         对话ID
     * @param pageSize       页面大小
     * @param lastCreateTime 最后一条记录的创建时间
     * @param request        请求
     * @return 对话历史分页
     */
    @GetMapping("/history/{chatId}")
    @AuthCheck(mustRole = UserConstant.USER_ROLE)
    public BaseResponse<Page<ChatHistory>> listChatHistory(
                                                    @PathVariable Long chatId,
                                                    @RequestParam(defaultValue = "10") int pageSize,
                                                    @RequestParam(required = false) String lastCreateTime,  // 接收字符串
                                                    HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LocalDateTime lastCreateTimeDate = null;
        if (StrUtil.isNotBlank(lastCreateTime)) {
            // 定义格式化器，匹配前端格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 解析字符串（默认使用系统时区，如需明确时区可加.withZone(ZoneId.of("时区"))）
            lastCreateTimeDate = LocalDateTime.parse(lastCreateTime, formatter);
        }
        Page<ChatHistory> result = chatHistoryService.listChatHistoryByPage(
                chatId, pageSize, lastCreateTimeDate, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 根据用户 ID 获取用户所有对话历史，并按对话 ID 分组返回每组最早的消息，消息按照创建时间降序排序（8.29 -> 8.27 -> 8.11）
     * @param userId 用户 ID
     * @return 按对话ID分组的 earliest 消息映射表
     */
    @GetMapping("/history/earliest/{userId}")
    @AuthCheck(mustRole = UserConstant.USER_ROLE)
    public BaseResponse<Map<Long, List<ChatHistory>>> getEarliestMessageByConversation(@PathVariable Long userId) {
        //1.基础校验
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户ID不能为空");
        //2.判断该用户是否存在
        User user = userService.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        //3.获取用户所有对话历史
        Map<Long, List<ChatHistory>> earliestMessageByConversation = chatHistoryService.getEarliestMessageByConversation(userId);
        return ResultUtils.success(earliestMessageByConversation);
    }

    /**
     * 根据对话 ID 删除对话历史记录（逻辑删除）
     * @param chatId 对话ID
     * @return 是否成功
     */
    @PostMapping("/history/delete/{chatId}")
    @AuthCheck(mustRole = UserConstant.USER_ROLE)
    public BaseResponse<Boolean> deleteChatHistoryByChatId(@PathVariable Long chatId) {
        //1.基础校验
        ThrowUtils.throwIf(chatId == null || chatId <= 0, ErrorCode.PARAMS_ERROR, "对话ID不能为空");
        //2.删除对话历史记录
        boolean result = chatHistoryService.deleteChatHistoryByChatId(chatId);
        return ResultUtils.success(result);
    }

}
